//
//  HomeHeadCellModel.swift
//  EasePods
//
//  Created by 易先生 on 2024/4/25.
//

import Foundation
import CRPEarPhone
import AVFoundation
import RxCocoa
import RxSwift
import AVFoundation
import EarbudsDatabase

public class HomeHeadCellModel: ViewModel {
    
    private var volumeObservation: NSKeyValueObservation?
    
    public let isConnected = BehaviorRelay(value: false)
    
    //    音量设置
    //    1.首次安装：系统的手机音量
    //    1.耳机仓、耳机未连最后一次同步耳机设置的音量(不可手动拖动和调节音量)
    //    2.耳机仓已连接并且耳机已连接同步耳机音量(可通过系统按键调整音量)
    public let sliderValue = BehaviorRelay<Float>(value: 0.5)
    
    /// 设置音量
    public let setVolumeValue = PublishRelay<Float>()
    
    public let batteryInfo  = BehaviorRelay<CRPEarPhone.CRPBatteryInfoModel?>(value: nil)
    
    public let receiveEarPhoneConnectionState = BehaviorRelay<CRPEarPhone.CRPEarPhoneConnectStateModel?>(value: nil)
    
    public let useTime = BehaviorRelay<Int?>(value: nil)
    
    public override init() {
        super.init()
        
        BluetoothManager.shared.connectState
            .map{ _ in return BluetoothManager.shared.isConnected }
            .distinctUntilChanged()
            .bind(to: self.isConnected)
            .disposed(by: rx.disposeBag)
        
        BluetoothManager.shared.receiveEarPhoneConnectionState
            .bind(to: self.receiveEarPhoneConnectionState).disposed(by: rx.disposeBag)
        
        BluetoothManager.shared.receiveBatteryInfo
            .bind(to: self.batteryInfo).disposed(by: rx.disposeBag)
        
        BluetoothManager.shared.queryEarPhoneAudio().map{ Float($0.volume) }
            .bind(to: self.sliderValue).disposed(by: rx.disposeBag)
        
        ///设置
        setVolumeValue.subscribe(onNext: { [weak self] volume in
            guard let self = self else { return }
            self.sendEarVolume(volume: Int(volume))
        }).disposed(by: rx.disposeBag)
        
        BluetoothManager.shared.receiveUseTime
            .map { EasepodsDB.queryDay(type: UsetimeModel.self, from: Date())?.totalTimeMin }
            .bind(to: useTime).disposed(by: rx.disposeBag)
        
        
        // 获取音频会话的实例
        let audioSession = AVAudioSession.sharedInstance()
        
        // 激活音频会话
        do {
            try audioSession.setActive(true)
            let systemVolume = convertVolumeToLevel(volume: audioSession.outputVolume)
            sliderValue.accept(Float(systemVolume))
        } catch {
            log.debug("Failed to activate audio session: \(error)")
        }
        
        // 打印初始音量
        log.debug("Initial volume: \(audioSession.outputVolume)")
        
        // 监听音量变化
        volumeObservation = audioSession.observe(\.outputVolume, options: [.new]) { [weak self] (audioSession, change) in
            guard let self = self else { return }
            if let newVolume = change.newValue {
                print("\(newVolume)")
                let volume = convertVolumeToLevel(volume: newVolume)
                self.sliderValue.accept(Float(volume))
                self.sendEarVolume(volume: volume)
            }
        }
        
    }
    
    private func sendEarVolume(volume: Int) {
        log.debug("发送音量给耳机\(volume)")
        BluetoothManager.shared.sendEarPhoneVolume(value: volume)
    }
    
    private func convertVolumeToLevel(volume: Float) -> Int {
        return Int(ceil(volume * MaxVolume))
    }
    
    private func convertLevelToVolume(level: Int) -> Float {
        return Float(level) / MaxVolume
    }
    
    
    deinit {
        let audioSession = AVAudioSession.sharedInstance()
        do {
            try audioSession.setActive(false)
        } catch {
            log.debug("Failed to set up audio session: \(error)")
        }
        volumeObservation?.invalidate()
    }
}
